package com.qtx.report.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qtx.report.common.CommonMethod;
import com.qtx.report.common.pojo.BaseEntity;
import com.qtx.report.entity.SysRoleMenu;
import com.qtx.report.entity.SysUserRole;
import com.qtx.report.mapper.SysRoleMenuMapper;
import com.qtx.report.pojo.dto.SysRoleMenuDto;
import com.qtx.report.pojo.vo.SysRoleMenuVo;
import com.qtx.report.service.ISysRoleMenuService;
import com.qtx.report.service.ISysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色菜单关系表 服务实现类
 * </p>
 *
 * @author qtx
 * @since 2022-09-21
 */
@Service
public class SysRoleMenuServiceImpl extends ServiceImpl<SysRoleMenuMapper, SysRoleMenu> implements ISysRoleMenuService {

    @Autowired
    private SysRoleMenuMapper mapper;
    @Autowired
    private CommonMethod commonMethod;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @Override
    public List<SysRoleMenuVo> getMenuByRole() {
        String username = commonMethod.getUser().getUsername();
        List<String> roleByUser = sysUserRoleService.getRoleByUser(username)
                .stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());
        return mapper.selectByRoleId(Wrappers.lambdaQuery(SysRoleMenu.class).in(SysRoleMenu::getRoleId, roleByUser));
    }

    @Override
    public boolean saveOrUpdateNew(SysRoleMenuDto dto) {
        remove(Wrappers.lambdaUpdate(SysRoleMenu.class)
                .set(BaseEntity::getDeleteFlag, "1")
                .eq(SysRoleMenu::getRoleId, dto.getRoleId()));
        List<SysRoleMenu> list = new ArrayList<>();
        dto.getMenuIdList().forEach(e -> {
            SysRoleMenu menu = new SysRoleMenu();
            menu.setMenuId(e);
            menu.setRoleId(dto.getRoleId());
            list.add(menu);
        });
        return saveBatch(list);
    }
}
